package com.liu.design.structure.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author LIU
 * @version 1.0
 * @description: TODO
 * @date 2022/12/19 16:19
 */
public class JdkProxyUtil<T>  implements InvocationHandler {

    private T target;

    public JdkProxyUtil(T target) {
        this.target = target;
    }

    /**
     * 定义目标方法的拦截逻辑：每个方法都会进入
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("前置处理，代理类："+ proxy.getClass());
        Object invoke = method.invoke(target, args);
        System.out.println("后置处理");
        return invoke;
    }

    /**
     * 获取被代理对象的 代理对象
     * @param t
     * @param <T>
     * @return
     */
    public static<T> T  getProxy(T t) {

        Object instance = Proxy.newProxyInstance(
                t.getClass().getClassLoader(),
                t.getClass().getInterfaces(),
                new JdkProxyUtil(t));

        return (T) instance;
    }

}
